package chase.myrewards;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;

/**
 * Main display activity.  This activity has an Android WebView object that
 * is able to display HTML.  This activity displays the account list view, 
 * account info view, the breakdown of used points, and the breakdown of 
 * recently earned points.  It also has a logout button and a button that
 * takes the user to the location activity.
 * 
 * @author Meena Abdou
 * @date 04/25/2013
 */

public class InfoActivity extends Activity {

	public static final int INFO_ACTIVITY = 2;
	private WebView myWebView;
	private ProgressBar progressBar;
	private Button locationBtn;
	private Button logoutBtn;
	private BroadcastReceiver receiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.info);
		
		// Receiver used to kill the activity when exit button is pressed
		receiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				finish();
			}
		};

		IntentFilter filter = new IntentFilter();

		filter.addAction("chase.myrewards.finish");
		registerReceiver(receiver, filter);

		try{
			loadPreferences();  // load preferences from customer bean into shared preferences

			String url = "http://my-rewards.appspot.com/accountlist";
			//String url = "http://192.168.1.4:8888/accountlist";
			//String url = "http://128.4.125.128:8888/accountlist";

			locationBtn = (Button) findViewById(R.id.goToLocation);
			
			// Initially gone because we don't know what the settings are at this point
			locationBtn.setVisibility(View.GONE);
			
			locationBtn.setOnClickListener(new View.OnClickListener() {        	
				public void onClick(View v) {
					Intent i = new Intent(getApplicationContext(), LocationActivity.class);
					startActivityForResult(i, LocationActivity.LOCATION_ACTIVITY);
				}
			});

			logoutBtn = (Button) findViewById(R.id.logoutButton);

			logoutBtn.setOnClickListener(new View.OnClickListener() {        	
				public void onClick(View v) {
					logout();
					
					// Kill other activities
					Intent finish = new Intent();
					finish.setAction("chase.myrewards.finish");
					sendBroadcast(finish);
					
					// Go back to the account login activity
					Intent i = new Intent(getApplicationContext(), AppLoginActivity.class);
					startActivity(i);
				}
			});

			myWebView = (WebView) findViewById(R.id.webview);
			progressBar = (ProgressBar) findViewById(R.id.progressBar);

			// Synchronize cookies and session data so server doesn't see 2 different clients
			MyRewardsClient.getInstance().syncSession(myWebView.getContext());
			
			myWebView.setWebViewClient(new MyRewardsWebClient());
			myWebView.getSettings().setJavaScriptEnabled(true);
			
			new AsyncTask<String, Void, Integer>() {

				@Override
				protected Integer doInBackground(String... url) {
					myWebView.loadUrl(url[0]);
					return 0;
				}
				
			}.execute(url);
		}
		catch (Exception e){
			Log.e("InfoActivity", "Exception", e);
		}
	}
	
	@Override
	protected void onDestroy(){
		super.onDestroy();
		unregisterReceiver(receiver);
		receiver = null;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == PrefsActivity.PREFS_ACTIVITY){
			savePreferences();
		}
		checkShowLocations();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// Check if the key event was the Back button and if there's history
		if (keyCode == KeyEvent.KEYCODE_BACK){
			if (myWebView.canGoBack()) { 
				myWebView.goBack();
				Log.d("InfoActivity", "After going back, url is " + myWebView.getUrl());
			}
			return true;  //This prevents it from going back to login activity
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu){
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item){ 	
		//check selected menu item
		if(item.getItemId() == R.id.exit){
			// Logout
			logout();
			
			// Kill all activities
			Intent finish = new Intent();
			finish.setAction("chase.myrewards.finish");
			sendBroadcast(finish);

			return true;
		}

		else if(item.getItemId() == R.id.about){
			AboutDialog about = new AboutDialog(this);
			about.setTitle("About MyRewards");
			about.show();
			return true;
		}

		else if(item.getItemId() == R.id.help){
			Intent intent = new Intent(getApplicationContext(), HelpActivity.class);
			startActivity(intent);
			return true;
		}

		else if(item.getItemId() == R.id.preferences){
			Intent intent = new Intent(getApplicationContext(), PrefsActivity.class);
			startActivityForResult(intent, PrefsActivity.PREFS_ACTIVITY);
			return true;
		}

		else{
			return super.onOptionsItemSelected(item);
		}
	}

	public void loadPreferences(){
		// Set preferences for customer
		SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
		SharedPreferences.Editor editor = sharedPref.edit();
		editor.putString(PrefsActivity.PASSWORD, MyRewardsClient.getInstance().getCustomer().getPassword());
		editor.putBoolean(PrefsActivity.SHOW_LOCATIONS, MyRewardsClient.getInstance().getCustomer().getShowLocations());
		editor.putBoolean(PrefsActivity.FAVORITES, MyRewardsClient.getInstance().getCustomer().getFavorites());
		editor.putBoolean(PrefsActivity.RECENT, MyRewardsClient.getInstance().getCustomer().getRecent());
		editor.commit();
	}

	public void savePreferences(){
		SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

		String password = sharedPref.getString(PrefsActivity.PASSWORD, ""); // default no password
		boolean showLocations = sharedPref.getBoolean(PrefsActivity.SHOW_LOCATIONS, true);  // default true
		boolean favorites = sharedPref.getBoolean(PrefsActivity.FAVORITES, true);  // default true
		boolean recent = sharedPref.getBoolean(PrefsActivity.RECENT, true);  // default true

		Log.d("InfoActivity", "New password is " + password);
		Log.d("InfoActivity", "New show_locations is " + showLocations);
		Log.d("InfoActivity", "New favorites is " + favorites);
		Log.d("InfoActivity", "New recent is " + recent);

		MyRewardsClient.getInstance().getCustomer().setPassword(password);
		MyRewardsClient.getInstance().getCustomer().setShowLocations(showLocations);
		MyRewardsClient.getInstance().getCustomer().setFavorites(favorites);
		MyRewardsClient.getInstance().getCustomer().setRecent(recent);
	}

	public void checkShowLocations(){
		SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
		boolean showLocations = sharedPref.getBoolean(PrefsActivity.SHOW_LOCATIONS, true);  // default true
		if (showLocations == false){
			locationBtn.setVisibility(View.GONE);
		}
		else{
			locationBtn.setVisibility(View.VISIBLE);
		}
	}

	public void logout(){
		String url = "http://my-rewards.appspot.com/logout";
		//String url = "http://192.168.1.4:8888/logout";

		// Call logout in MyRewardsClient to delete data and clear caches
		MyRewardsClient.getInstance().setUrl(url);
		MyRewardsClient.getInstance().Logout();
		MyRewardsClient.getInstance().setLoggedIn(false);		
	}

	/**
	 * This class handles the GUI while loading a new url.  If the url is the account list
	 * page, then the locations button is hidden.  Furthermore, after every url is loaded
	 * we check the show_locations setting because it may have been changed.
	 * 
	 * @author Meena Abdou
	 *
	 */
	private class MyRewardsWebClient extends WebViewClient{
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			try{
				Log.d("InfoActivity", "Now loading " + url);
				//MyRewardsClient.getInstance().setUrl(url);
				//MyRewardsClient.getInstance().Execute(RequestMethod.GET, true);
				//String data = MyRewardsClient.getInstance().getResponse();
				//view.loadData(data, "text/html", null);
				view.loadUrl(url);
			}
			catch (Exception e){
				Log.e("InfoActivity", "Exception", e);
			}
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			progressBar.setVisibility(View.GONE);
			if(myWebView.getUrl().contains("accountlist") || myWebView.getTitle().equalsIgnoreCase("error")){
				locationBtn.setVisibility(View.GONE);
			}
			else{
				checkShowLocations();  // Hide location button if showLocations is false
			}
		}
	}
}
